package com.yuke.cloud.service.omc.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.omc.dto.OrderProdDto;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsOrderGoods;
import com.yuke.cloud.service.omc.redis.RedisCacheTemplate;
import com.yuke.cloud.service.omc.service.OdsExcelImportService;
import com.yuke.cloud.service.omc.service.OdsOrderGoodsService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import com.yuke.cloud.service.omc.utils.SequenceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.IntStream;

@Service
@Transactional
@Slf4j
public class OdsExcelImportServiceImpl extends BaseService<OdsOrder> implements OdsExcelImportService {

    @Autowired
    private PmcFeignApi pmcFeignApi;

    @Autowired
    private SmcFeignApi smcFeignApi;

    @Autowired
    private OdsOrderService odsOrderService;

    @Autowired
    private UacUserFeignApi uacUserFeignApi;

    @Autowired
    private OdsOrderGoodsService odsOrderGoodsService;

    @Autowired
    private RedisCacheTemplate redisCacheTemplate;

    private static final String  SERIAL_NUM= "redis:serialNumber:";




    @Override
    public Map<String, String> getImportOrder(List<OrderProdDto> orderProdDtos) {

        /*OrderProdDto orderProdOld = new OrderProdDto();
        ArrayList<OrderProdDto> list = new ArrayList<>();
        Integer i = 0;
        Integer k = 0;
        String shopName = null;
        if (orderProdDtos != null && orderProdDtos.size() > 0) {
            for (OrderProdDto orderProdDto : orderProdDtos) {
                k++;
                //店铺名
                //String shopName = orderProdDto.getShopName();
                if (shopName == null){
                    shopName = orderProdDto.getShopName();

                }

                if (shopName == orderProdDto.getShopName()){
                    i += orderProdDto.getPurchasePrice();
                    list.add(orderProdDto);
                    orderProdOld = orderProdDto;
                }else{
                    orderProdDto.setProductPriceTotal(i);
                    doImportOrder(orderProdOld);
                    doImportOrderGoods(list);
                    shopName = orderProdDto.getShopName();
                    list.clear();
                    list.add(orderProdDto);
                    i= orderProdDto.getPurchasePrice();
                }

                if (k == orderProdDtos.size()){
                    orderProdDto.setProductPriceTotal(i);
                    doImportOrder(orderProdOld);
                    doImportOrderGoods(list);
                }

            }

        }*/


        return null;
    }

    /**
     * 导入前预处理：店铺名称未找到时，要创建用户、店铺
     * @param orderProdDtoList
     * @return
     */
    @Override
    public String checkTable(List<OrderProdDto> orderProdDtoList) {
        System.out.println(orderProdDtoList);
        Set<String> set = new HashSet<>();
        String str="预处理报告：";

        if (orderProdDtoList == null || orderProdDtoList.size() <1){
            return "输入的数据为空！";
        }

        String shopName = "";
        Integer i=0,j=0;

        for (OrderProdDto orderProdDto : orderProdDtoList){
            //处理店铺名称
            if (!shopName.equals(orderProdDto.getShopName())){
                shopName = orderProdDto.getShopName();
                List<ShopInfoDto> shops = smcFeignApi.getShopInfoByShopName(shopName);
                if (shops != null && shops.size() > 0){
                    i++;
                    shopName = shops.get(0).getShopName();
                }else{
//                    //创建账户和店铺

                    String phoneNumber = orderProdDto.getPhoneNumber() !="" ?orderProdDto.getPhoneNumber() : "99"+String.valueOf(super.generateId()).substring(9,18);
                    String wareHouseId = ""+orderProdDto.getWareHouseId();
                    String address =""+orderProdDto.getAddress();
                    JSONObject jsonObject= new JSONObject();
                    jsonObject.put("shopName",orderProdDto.getShopName());
                    jsonObject.put("phoneNumber",phoneNumber);
                    jsonObject.put("address",address);
                    jsonObject.put("wareHouseId",wareHouseId);
                    Integer num =uacUserFeignApi.autoRegisterUserAndShop(jsonObject);

                    if (num != null && num > 0) {
                        j = j + num;
                    }
                    j++;
                    set.add(orderProdDto.getShopName());
                }
            }


        }
        str +="能识别的店铺名称数："+i+"\n";
        str +="不能识别的店铺名称数："+j+"\n";
        str +="未匹配到店名的记录："+set+"\n";
        System.out.println("未匹配到店名的记录："+set);
        str +="店铺名称生成新账号。";
        System.out.println(str);
        return str;
    }

    /**
     * 导入前，检测店铺名称，没有找到的店铺返回名称，以便修正
     * @param orderProdDtoList
     * @return
     */
    @Override
    public String checkShopName(List<OrderProdDto> orderProdDtoList) {
        Set<String> set = new HashSet<>();
        String str="检测店铺名称报告：";

        if (orderProdDtoList == null || orderProdDtoList.size() <1){
            return "输入的数据为空！";
        }

        String shopName = "";
        Integer i=0,j=0;

        for (OrderProdDto orderProdDto : orderProdDtoList) {
            //处理店铺名称
            if (!shopName.equals(orderProdDto.getShopName())) {
                shopName = orderProdDto.getShopName();
                List<ShopInfoDto> shops = smcFeignApi.getShopInfoByShopName(shopName);
                if (shops != null && shops.size() > 0) {
                    i++;
                    shopName = shops.get(0).getShopName();
                } else {
                    j++;
                    set.add(orderProdDto.getShopName());
                }
            }
        }
        str +="能识别的店铺名称数："+i+"\n";
        str +="不能识别的店铺名称数："+j+"\n";
        str +="未匹配到店名的记录："+set+"\n";
        System.out.println("未匹配到店名的记录："+set);

        return str;
    }

    /**
     * 导入前，检测导入的商品名称，没有找到的返回，以便修正
     * @param orderProdDtoList
     * @return
     */
    @Override
    public String checkSpecName(List<OrderProdDto> orderProdDtoList) {
        Set<String> set2 = new HashSet<>();
        String str="检测商品名称报告：";
        String noIdentify="未识别的商品为：";
        if (orderProdDtoList == null || orderProdDtoList.size() <1){
            return "输入的数据为空！";
        }

        Integer k=0,l=0,m=0,n = 0;

        for (OrderProdDto orderProdDto : orderProdDtoList){
            //处理商品名称
            if (orderProdDto.getShopName() != null){
                List<ProdSpecInfoDto> importSpecId =findSpecId( orderProdDto.getSpecName());
                if (importSpecId != null && importSpecId.size() > 0){
                    k++;
                    Integer pp = 5000;
                    ProdSpecInfoDto prodSpecInfoDto = new ProdSpecInfoDto();
                    for (ProdSpecInfoDto  item: importSpecId){
                        Integer qq = Math.abs(item.getStockPrice()- orderProdDto.getGoodsPrice());
                        if (pp > qq ){
                            pp = qq;
                            prodSpecInfoDto = item;

                        }
                    }
                    if (prodSpecInfoDto != null && prodSpecInfoDto.getSpecName() !=null){
                        if (orderProdDto.getGoodsPrice().equals(prodSpecInfoDto.getStockPrice())){
                            m++;
                            // System.out.println("识别商品1："+orderProdDto.getRowId()+","+orderProdDto.getShopName()+","+orderProdDto.getSpecName()+","+orderProdDto.getGoodsPrice());
                            // System.out.println("精准匹配商品："+orderProdDto.getRowId()+","+prodSpecInfoDto.getSpecName()+","+prodSpecInfoDto.getStockPrice());

                        }else {
                            n++;
                            // System.out.println("识别商品2：" +orderProdDto.getRowId()+","+ orderProdDto.getShopName() + "," + orderProdDto.getSpecName() + "," + orderProdDto.getGoodsPrice());
                            // System.out.println("近似匹配商品：" +orderProdDto.getRowId()+","+ prodSpecInfoDto.getSpecName() + "," + prodSpecInfoDto.getStockPrice());

                        }
                    }else{
                        prodSpecInfoDto = importSpecId.get(0);
                        set2.add(orderProdDto.getSpecName());
                        System.out.println("识别商品3："+orderProdDto.getRowId()+","+orderProdDto.getShopName()+","+orderProdDto.getSpecName()+ "," + orderProdDto.getGoodsPrice());
                        System.out.println("误差匹配商品："+orderProdDto.getRowId()+","+prodSpecInfoDto.getSpecName()+","+prodSpecInfoDto.getStockPrice());

                    }

                }else{
                    l++;
                    noIdentify += orderProdDto.getShopName()+","+orderProdDto.getSpecName()+"\n";
                    System.out.println("未识别商品:"+orderProdDto.getRowId()+orderProdDto.getShopName()+","+orderProdDto.getSpecName());
                }
            }
        }

        str +="商品识别数="+k+",商品未识别数="+l+"\n";
        str +="精准匹配:"+m+","+"近似匹配:"+n+"\n";
        str +="误差匹配："+set2.toString();
        if (l > 0){
            str += noIdentify;
        }
        System.out.println(str);
        return str;

    }


    /**
     * 导入
     * @param orderProdDtos
     * @return
     */
    public Map<String, Integer> doIt(List<OrderProdDto> orderProdDtos) {
        ArrayList<OrderProdDto> list = new ArrayList<>();
        Map<String, Integer> map =new HashMap<>();
        map.put("orderSuccess",0);
        map.put("goodsSuccess",0);
        map.put("orderFailure",0);
        map.put("goodsFailure",0);
        Integer k = 0;
        String shopName = null;
        if (orderProdDtos != null && orderProdDtos.size() > 0) {
            for (OrderProdDto orderProdDto : orderProdDtos) {
                //店铺名

                if (shopName == null){
                    shopName = orderProdDto.getShopName();
                }
                if (shopName.equals(orderProdDto.getShopName())){
                    list.add(orderProdDto);
                }else{

                    Map<String, Integer> map1 =doImportOrder(list);
                    if (!map1.isEmpty()){
                        map.put("orderSuccess",map.get("orderSuccess")+map1.get("orderSuccess"));
                        map.put("goodsSuccess",map.get("goodsSuccess")+map1.get("goodsSuccess"));
                        map.put("orderFailure",map.get("orderFailure")+map1.get("orderFailure"));
                        map.put("goodsFailure",map.get("goodsFailure")+map1.get("goodsFailure"));
                    }
                    shopName = orderProdDto.getShopName();
                    list.clear();
                    list.add(orderProdDto);
                }
                if (k == orderProdDtos.size()-1){
                    Map<String, Integer> map2=doImportOrder(list);
                    if (!map2.isEmpty()) {
                        map.put("orderSuccess", map.get("orderSuccess") + map2.get("orderSuccess"));
                        map.put("goodsSuccess", map.get("goodsSuccess") + map2.get("goodsSuccess"));
                        map.put("orderFailure", map.get("orderFailure") + map2.get("orderFailure"));
                        map.put("goodsFailure", map.get("goodsFailure") + map2.get("goodsFailure"));
                    }
                }
                k++;
            }
        }
        return map;
    }

    /**
     * 批量导入订单
     *
     * @param orderProdDto
     * @return
     */
    public Map<String, Integer> doImportOrder(List<OrderProdDto> orderProdDto) {
        Map<String, Integer> map = new HashMap<>();
        Long shopId = 0L;
        Long userId = 0L;
        Long regionCountyId=0L;
        Long regionCityId=0L;
        Long regionProvinceId=0L;
        int success=0;
        int failure=0;

        IntStream intStream = orderProdDto.stream().mapToInt(OrderProdDto::getGoodsPrice);
        int sum = intStream.sum();

        List<ShopInfoDto> shops = smcFeignApi.getShopInfoByShopName(orderProdDto.get(0).getShopName().trim());
        if( shops != null && shops.size()>0){
            shopId = shops.get(0).getShopId();
            userId = shops.get(0).getUserId();
            regionCountyId = shops.get(0).getRegionCountyId();
            regionCityId =  shops.get(0).getRegionCityId();
            regionProvinceId = shops.get(0).getRegionProvinceId();
        }

        OdsOrder odsOrder = new OdsOrder();
        Long orderId=super.generateId();
        odsOrder.setOrderId(orderId);

        Long timeStamp = Long.valueOf(orderProdDto.get(0).getPayTime());
        timeStamp =((timeStamp-25569) * 24*60*60-8*3600)*1000;
        odsOrder.setPayTime(new Date(timeStamp));
        odsOrder.setCreateTime(new Date(timeStamp));

        UUID id = UUID.randomUUID();
        String[] idd = id.toString().split("-");
        String uuid20 = idd[0] + idd[1] + idd[2] + idd[3];
        //12位长度,相加一共生成32位的订单号
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date(timeStamp));
        String key = SERIAL_NUM + currentDate;
        long incr = redisCacheTemplate.incr(key, 1, 86400);
        //移位运算符<<，左移几位相当于乘以2的几次方, 1 << 2 = 4
        String code = SequenceUtils.getSequence(incr, 1 << 2);
        odsOrder.setOrderSn(uuid20 + currentDate + code);

        odsOrder.setShopId(shopId);
        odsOrder.setShippingStatus((byte)3);
        odsOrder.setOrderStatus((byte)2);
        odsOrder.setOrderType((byte)2);
        odsOrder.setPayType((byte)0);
        odsOrder.setCommissionStatus((byte)0);
        odsOrder.setPayStatus((byte)1);
        odsOrder.setUserId(userId);
        odsOrder.setConsignee(shops.get(0).getShopName());
        odsOrder.setAmountPaid(sum - (Integer.valueOf(String.valueOf(Math.round(sum * 0.03)))));
        odsOrder.setAmountPayable(sum);
        odsOrder.setRegionCountyId(regionCountyId);
        odsOrder.setRegionCityId(regionCityId);
        odsOrder.setRegionProvinceId(regionProvinceId);
        odsOrder.setProductPriceTotal(sum);
        odsOrder.setWarehouseId(Long.parseLong(orderProdDto.get(0).getWareHouseId()));
        odsOrder.setMobile(shops.get(0).getTelephone());


        odsOrder.setDiscount(Integer.valueOf(String.valueOf(Math.round(sum * 0.03))));

        int count = odsOrderService.save(odsOrder);
        if (count>=1){
             map = doImportOrderGoods(orderId, orderProdDto);
            success++;
        }else {
            failure++;
        }
        map.put("orderSuccess",success);
        map.put("orderFailure",failure);
        return map;
    }

    public Map<String, Integer> doImportOrderGoods(Long orderId, List<OrderProdDto> orderProdDto) {

        Map<String,Integer> map = new HashMap<>();
        //根据产品名获取产品Id
        int success=0;
        int failure=0;
        for (OrderProdDto prodDto : orderProdDto) {
            List<ProdSpecInfoDto> importSpecId =findSpecId( prodDto.getSpecName());
            if (importSpecId !=null && importSpecId.size()>=1){
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                //odsOrderGoods.setSpecId(prodDto.getSpecId());
                odsOrderGoods.setSpecId(importSpecId.get(0).getSpecId());
                odsOrderGoods.setProductId(importSpecId.get(0).getProductId());
                odsOrderGoods.setOrderId(orderId);
                odsOrderGoods.setGoodsPrice(prodDto.getGoodsPrice());
                odsOrderGoods.setPayPrice(prodDto.getGoodsPrice());
                odsOrderGoods.setGoodsNum(prodDto.getGoodsNum());
                odsOrderGoods.setGoodsWeight(importSpecId.get(0).getWeight());

                int count = odsOrderGoodsService.save(odsOrderGoods);
                if (count==1){
                    success++;
                }
            }else {
                failure++;
            }

        }
        map.put("goodsSuccess",success);
        map.put("goodsFailure",failure);

        return map;
    }


    public List<ProdSpecInfoDto> findSpecId(String specName){
        Integer len = specName.length();
        List<ProdSpecInfoDto> importSpecId = pmcFeignApi.getImportSpecId(specName);
        if (importSpecId.size()<1 || importSpecId == null){

            if(specName.length()>1){
                if(specName.length() == 5){
                    importSpecId= findSpecId(specName.substring(1,specName.length()));
                }else{
                    importSpecId = findSpecId(specName.substring(0,specName.length()-1));
                }
            }
        }
        return importSpecId;
    }


}
